package cancal;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class OperaOnNewsPaper implements Cloneable {

    private static Connection connection = Connect_MySQL.getConnection();


    /**
     * 支持批量插入数据
     */

    public void addNewsPaper() {
        String sql = "insert into t1 (id, name, jsid, xgsj) values(?, ?, ?, ?)";
        java.sql.PreparedStatement ptmt = null;

        try {
            connection.setAutoCommit(false);// 关闭事务
            ptmt = connection.prepareStatement(sql);

        } catch (SQLException e2) {
            e2.printStackTrace();
        }

        for (int i = 0; i < 1000000; i++) {

            try {
                ptmt.setLong(1, i);
                ptmt.setString(2, "chb" + i);
                ptmt.setString(3, "-1");
                ptmt.setString(4, "2099-01-01 00:00:00");
                ptmt.addBatch();
                if (i % 10000 == 0) {
					try {
						ptmt.executeBatch(); //执行给定的SQL语句，该语句可能返回多个结果
						connection.commit();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        try {
            ptmt.executeBatch();//执行给定的SQL语句，该语句可能返回多个结果
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void updateNewsPaper() {
        String sql = "update t1 set name = ? where id = ?";
        java.sql.PreparedStatement ptmt = null;

        try {
            connection.setAutoCommit(false);// 关闭事务
            ptmt = connection.prepareStatement(sql);

        } catch (SQLException e2) {
            e2.printStackTrace();
        }

        for (int i = 0; i < 1000000; i++) {
            try {
                ptmt.setString(1, "chb0902xw" + i);
                ptmt.setLong(2, i);
                ptmt.addBatch();
                if (i % 1000 == 0) {
                    try {
                        ptmt.executeBatch(); //批量提交
                        connection.commit();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        try {
            ptmt.executeBatch(); //执行给定的SQL语句，该语句可能返回多个结果
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        OperaOnNewsPaper operation = new OperaOnNewsPaper();
        operation.addNewsPaper();
        // operation.updateNewsPaper();
        long end = System.currentTimeMillis();
        System.out.println("cost time: " + (end - start) + "ms");
    }
}